

import {
    toast
} from 'nc-lightapp-front';

import toggleTableCheckboxAble from './functions/toggleTableCheckboxAble';
import getSavePostData from './functions/getSavePostData';
import selectTableRows from './functions/selectTableRows';
import deepcopy from 'src/hrpub/common/utils/deep-copy.js'

export default class Actions {
    constructor(comp) {
        this.comp = comp;
        Object.assign(this, comp.props);
    }

    // 初始化页面
    init = () => {
        this.getLanguage();
        return this.getTemplate()
            .then(() => {
                this.comp.action.ButtonAction.initPageButton();
                this.initDefaultData()
                    .then((orgValue) => {
                        this.getTreeData(orgValue)
                    });
                // 设置两个表格的复选框禁用
                toggleTableCheckboxAble({
                    editTable: this.editTable
                }, false);
            });
    }

    initDefaultData = () => {
        return new Promise((resolve, reject) => {
            let currentTree = this.getUrlParam('selectedRow');
            let orgValue = decodeURIComponent(this.getUrlParam('orgValue'));
            let treeId = '';
            if (currentTree) {
                currentTree = JSON.parse(currentTree);
                treeId = currentTree.values['pk_rpt_def'].value;
                this.dispatch({
                    type: 'reportAss/update',
                    payload: {
                        currentTreeData: treeId
                    }
                });
            }
            if (orgValue && orgValue !== 'undefined') {
                orgValue = JSON.parse(orgValue);
                this.dispatch({
                    type: 'reportAss/update',
                    payload: {
                        orgValue: orgValue
                    }
                });
            }

            if (!/undefined/.test(currentTree) || !/undefined/.test(orgValue)) {
                this.getMainTableData({ orgValue: orgValue, currentTreeData: treeId })
                    .then(() => {
                        this.toAssignmentStatus(treeId)
                            .then(() => {
                                // // 因为设置参照值不好使，所以我就直接操作dom了哈
                                // let orgDom = document.querySelector('.header-refer .refer-input');
                                // orgDom && (orgDom.value = orgValue.refname);
                                this.comp.action.ButtonAction.toAssignmentStatus();
                            });
                    });
            }

            resolve(orgValue);
        });
    }

    selectRow = (props, tableId, record, index, status) => {
        const { reportAss } = this.comp.props;
        const { language } = reportAss;
        let v = status ? language['hi6007-000240'] : language['hi6007-000241']; //'浏览' : '未分配';
        let authValue = status ? '1' : '0';
        let tableDataName = tableId + 'Data'
        let result = deepcopy(reportAss[tableDataName]);
        result.rows[index].values['authName'].value = v;
        result.rows[index].values['auth'].value = authValue;
        this.editTable.setValByKeyAndRowId(tableId, record.rowid, 'authName', {
            value: v
        });
        this.editTable.setValByKeyAndRowId(tableId, record.rowid, 'auth', {
            value: authValue
        });
        this.dispatch({
            type: 'reportAss/update',
            payload: {
                [tableDataName]: result,
            }
        });
    }

    selectAllRow = (props, tableId, status, length) => {
        const { reportAss } = this.comp.props;
        const { language } = reportAss;
        let roleData = {};
        let userData = {};
        let v = status ? language['hi6007-000240'] : language['hi6007-000241']; //'浏览' : '未分配';
        let authValue = status ? '1' : '0';
        // if (reportAss.searchValue.length > 0) {
        //     roleData = reportAss.roleSearchData;
        //     userData = reportAss.userSearchData;
        // } else {
            roleData = deepcopy(reportAss.roleData);
            userData = deepcopy(reportAss.userData);
        // }
        if (tableId === 'role') {
            roleData.rows.map((item) => {
                item.values['authName'].value = v;
                item.values['auth'].value = authValue;
            })
        } else {
            userData.rows.map((item) => {
                item.values['authName'].value = v;
                item.values['auth'].value = authValue;
            })
        }
        this.dispatch({
            type: 'reportAss/update',
            payload: {
                roleData: roleData,
                userData: userData
            }
        });
    }

    // 获取模版
    getTemplate = () => {
        return new Promise((resolve, reject) => {
            this.createUIDom(this.appConfig, (res) => {
                this.dispatch({
                    type: 'reportAss/update',
                    payload: {
                        context: res.context
                    }
                });
                this.meta.setMeta(res.template);
                this.button.setButtons(res.button);
                resolve();
            });
        });

    }

    // 获取多语言
    getLanguage = () => {
        this.MultiInit.getMultiLang({
            moduleId: 'hi6007',
            domainName: 'hrhi',
            callback: (json, status, init) => {
                this.dispatch({
                    type: 'reportAss/update',
                    payload: {
                        language: json
                    }
                });
            }
        });
    }

    // 点击左树选择
    selectTree = (value) => {
        this.dispatch({
            type: 'reportAss/update',
            payload: {
                currentTreeData: value,
                searchValue:''
            }
        });
        this.getMainTableData({ currentTreeData: value,pageInfo:{pageIndex: 1,
            pageSize: 10,
            total: 0,
            totalPage: 1},v:'' });
    }

    // 获取左树数据
    getTreeData = (orgValue) => {
        const { currentTreeData } = this.comp.props.reportAss;
        let payload = {};
        orgValue && (payload['orgValue'] = orgValue)
        return this.dispatch({
            type: 'reportAss/getTreeData',
            payload: payload
        })
            .then((res) => {
                this.syncTree.setSyncTreeData('reportGroupTree', res.data);
                if (currentTreeData) {
                    this.syncTree.openNodeByPk('reportGroupTree', currentTreeData);
                    this.syncTree.setNodeSelected('reportGroupTree', currentTreeData);
                }
            });
    }

    // 切换内容tab
    onChangeTab = (value) => {
        this.dispatch({
            type: 'reportAss/update',
            payload: {
                activeTab: value,
            }
        });
        let searchValue = '';

        setTimeout(() => {
            //     toggleTableCheckboxAble({
            //         editTable: this.editTable
            //     }, this.comp.props.reportAss.editing);
            //     selectTableRows({
            //         editTable: this.editTable,
            //         state: this.comp.props.reportAss
            //     });
            this.searchChange({ v: searchValue });
            this.getMainTableData({v: searchValue})
        }, 1);
    }

    // 进入分配状态
    toAssignmentStatus = (treeId) => {
        const { reportAss, editTable, syncTree } = this.comp.props;
        const {
            currentTreeData,
            language
        } = reportAss;

        return new Promise((resolve, reject) => {
            if (!currentTreeData && !treeId) {
                toast({
                    color: 'warning',
                    content: language['hi6007-000239'] // '请先选中一个报表节点'
                });
                reject();
            }
            else {
                this.dispatch({
                    type: 'reportAss/checkAssignment',
                    payload: {
                        currentTreeData: treeId
                    }
                })
                    .then(async (res) => {
                        if (res.success) {
                            await this.dispatch({
                                type: 'reportAss/update',
                                payload: {
                                    editing: true
                                }
                            });
                            toggleTableCheckboxAble({
                                editTable: editTable
                            }, true);
                            syncTree.setNodeDisable('reportGroupTree', true);
                            resolve();
                        }
                    });
            }
        });
    }

    // 从分配态返回主表
    toMainPageStatus = () => {
        this.dispatch({
            type: 'reportAss/update',
            payload: {
                editing: false
            }
        });
        return new Promise((resolve, reject) => {
            toggleTableCheckboxAble({
                editTable: this.editTable
            }, false);
            this.syncTree.setNodeDisable('reportGroupTree', false);
            this.getMainTableData();
            resolve();
        });
    }

    // 获取主表数据
    getMainTableData = ({ orgValue, currentTreeData,pageInfo,index ,v} = {}) => {
        const {
            reportAss
        } = this.comp.props;
        !index && index === 0? index = 0 : index = -1
        if(v && v !== ''){
            index = (reportAss.activeTab === 'role'?0:1)
        }
        !v && (v = reportAss.searchValue)
        !pageInfo && (reportAss.activeTab === 'role'? pageInfo = reportAss.rolePageInfo:pageInfo = reportAss.userPageInfo)

        return this.dispatch({
            type: 'reportAss/getMainTableData',
            payload: {
                orgValue: orgValue ? orgValue : '',
                currentTreeData: currentTreeData ? currentTreeData : '',
                pageInfo,
                index:index,
                searchWord:v
            }
        })
            .then((res) => {
                let roleCheckedList = [];
                let roleUnCheckedList = [];
                let userCheckedList = [];
                let userUnCheckedList = [];
                let rolePageInfo = {}
                let userPageInfo = {}
                let resultRole = null;
                let resultUser = null;
                if (res.data &&(res.data.role || res.data.user)) {
                    if (res.data.role){
                        res.data.role.role.rows.map((item, index) => {
                            if (/^1$/.test(item.values['auth'].value)) {
                                roleCheckedList.push(index);
                            }
                            else {
                                roleUnCheckedList.push(index);
                            }
                        });
                        rolePageInfo = deepcopy(res.data.role.role.pageInfo)
                        resultRole = deepcopy(res.data.role.role)
                        this.dispatch({
                            type: 'reportAss/update',
                            payload: {
                                roleData: res.data.role.role,
                                rolePageInfo:{
                                    ...rolePageInfo
                                },
                                roleCheckedList: roleCheckedList,
                                roleUnCheckedList: roleUnCheckedList,
                            }
                        });
                    }
                    if (res.data.user){

                        res.data.user.user.rows.map((item, index) => {
                            if (/^1$/.test(item.values['auth'].value)) {
                                userCheckedList.push(index);
                            }
                            else {
                                userUnCheckedList.push(index);
                            }
                        });
                        userPageInfo = deepcopy(res.data.user.user.pageInfo)
                        resultUser = deepcopy(res.data.user.user)
                        this.dispatch({
                            type: 'reportAss/update',
                            payload: {
                               userData: res.data.user.user,
                                userPageInfo:{
                                    ...userPageInfo
                                },
                                userCheckedList: userCheckedList,
                                userUnCheckedList: userUnCheckedList,
                            }
                        });

                    }
                    let roleReData = resultRole?{rows:resultRole.rows}:{rows:reportAss.roleData.rows}
                    let userReData = resultUser?{rows:resultUser.rows}:{rows:reportAss.userData.rows}
                    this.editTable.setTableData('role', roleReData, false);
                    this.editTable.setTableData('user',userReData, false);
                    this.checkedAndUnchecked({ v: v, roleData: resultRole, userData: resultUser })
                    // this.searchChange({ v: v})
                    this.dispatch({
                        type: 'reportAss/update',
                        payload: {
                            assignedRole: res.data.assignedRole ? res.data.assignedRole: [] , // 保存初始得到的已分配的数据
                            assignedUser: res.data.assignedUser ? res.data.assignedUser: []
                        }
                    })
                }
                else {
                    this.editTable.setTableData('role', { rows: [] }, false);
                    this.editTable.setTableData('user', { rows: [] }, false);
                    this.dispatch({
                        type: 'reportAss/update',
                        payload: {
                            roleCheckedList: roleCheckedList,
                            roleUnCheckedList: roleUnCheckedList,
                            userCheckedList: userCheckedList,
                            userUnCheckedList: userUnCheckedList,
                            rolePageInfo:{
                                pageIndex: 1,
                                pageSize: 10,
                                total: 0,
                                totalPage: 1
                            },
                            userPageInfo:{
                                pageIndex: 1,
                                pageSize: 10,
                                total: 0,
                                totalPage: 1
                            },
                            assignedRole: [], // 保存初始得到的已分配的数据
                            assignedUser: []
                        }
                    });
                }

            });
    }
    turnPage(type) {
        return(pageIndex)=>{
            let index = (type === 'rolePageInfo'?0:1)
            const {
                reportAss
            } = this.comp.props;
            let pageInfo = {
                ...reportAss[type],
                pageIndex: pageIndex
            };
            this.getMainTableData({pageInfo,index});
        }

    }
    changePageSize(type){
        return (pageSize) => {
            let index = (type === 'rolePageInfo'?0:1)
            const {
                reportAss
            } = this.comp.props;
            let pageInfo = {
                ...reportAss[type],
                pageSize: pageSize
            };
            this.getMainTableData({pageInfo,index});
        }
    }
    // 保存分配更改
    saveChange() {
        const {
            currentTreeData,
            language,
            orgValue,
            roleData,
            userData,
            assignedRole,
            assignedUser
        } = this.comp.props.reportAss;

        let postData = getSavePostData({
            editTable: this.editTable,
            currentTreeData: currentTreeData,
            orgValue: orgValue,
            roleData: roleData,
            userData: userData,
            assignedRole: assignedRole,
            assignedUser: assignedUser
        });

        this.dispatch({
            type: 'reportAss/saveAssignment',
            payload: {
                postData: postData
            }
        })
            .then((res) => {
                if (res.success) {
                    toast({
                        color: 'success',
                        content: language['hi6007-000000'] // 保存成功
                    });
                    this.toMainPageStatus();
                    this.comp.action.ButtonAction.toMainPageStatus();
                }
            });
    }

    // 搜索功能

    searchChange = ({ v } = {}) => {
        const { reportAss } = this.comp.props;
        this.dispatch({
            type: 'reportAss/update',
            payload: {
                searchValue: v,
            }
        });
        // this.getMainTableData({v: v})
    }

    checkedAndUnchecked = ({ v, roleData, userData } = {}) => {
        const { reportAss } = this.comp.props;
        !roleData && (roleData = reportAss.roleData);
        !userData && (userData = reportAss.userData);
        !v && (v = reportAss.searchValue)
        let roleCheckedList = [];
        let roleUnCheckedList = [];
        let userCheckedList = [];
        let userUnCheckedList = [];
        if (reportAss.activeTab === 'role') {
            if (roleData.rows.length === 0) {
                this.editTable.selectAllRows('role', false);
                return;
            }
        } else {
            if (userData.rows.length === 0) {
                this.editTable.selectAllRows('user', false);
                return;
            }
        }
        roleData && roleData.rows.map((item, index) => {
            if (/^1$/.test(item.values['auth'].value)) {
                roleCheckedList.push(index);
            }
            else {
                roleUnCheckedList.push(index);
            }
        })
        userData && userData.rows.map((item, index) => {
            if (/^1$/.test(item.values['auth'].value)) {
                userCheckedList.push(index);
            }
            else {
                userUnCheckedList.push(index);
            }
        })

        selectTableRows({
            editTable: this.editTable,
            state: {
                roleCheckedList: roleCheckedList,
                roleUnCheckedList: roleUnCheckedList,
                userCheckedList: userCheckedList,
                userUnCheckedList: userUnCheckedList
            }
        });
        if (reportAss.activeTab === 'role' && roleCheckedList.length === roleData.rows.length) {
            this.editTable.selectAllRows('role', true);
        }
        if (reportAss.activeTab === 'user' && userCheckedList.length === userData.rows.length) {
            this.editTable.selectAllRows('user', true);
        }
        toggleTableCheckboxAble({
            editTable: this.editTable
        }, this.comp.props.reportAss.editing);
    }
} 